package cn.guozeyiblog.client;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.guozeyiblog.blogutils.ArticleDetail;
import cn.guozeyiblog.client.MainAllAdapter.AsyGetCateList;
import cn.guozeyiblog.client.MainAllAdapter.AsyGetLinkList;
import cn.guozeyiblog.client.MainAllAdapter.AsyGetWechatList;
import cn.guozeyiblog.client.XListView.IXListViewListener;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.JsoupUtils;
import cn.guozeyiblog.netutils.NetWorkStatus;

public class SearchActivity extends Activity implements IXListViewListener {
	private EditText mEdit;
	private ImageView sImage;
	private XListView xList;
	private ProgressBar pBar;
	private ArrayList<ArticleDetail> alist;
	private ArticleAdapter adapter;
	private static String FLAG_ARTICLE_REFUSH="REFUSH";
	private static String FLAG_ARTICLE_LOAD="LOAD";
	private static String FLAG_ARTICLE_NODATA="NODATA";
	private String blogurl;
	private int pager=1;
	private String key;
	private LinearLayout adlayout;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_view);
		initView();
		alist = new ArrayList<>();
		adapter = new ArticleAdapter(alist, getApplicationContext());
		xList.setAdapter(adapter);
		xList.setPullLoadEnable(false);
		xList.setPullRefreshEnable(false);  //不能刷新
		xList.setXListViewListener(this);
		sImage.setEnabled(true);
		sImage.setClickable(true);
		blogurl = getSharedPreferences("emlog", Context.MODE_PRIVATE).getString("blogurl", "http://guozeyiblog.cn");
		AdView adView = new AdView(getApplicationContext(), AdSize.FIT_SCREEN);
		adlayout.addView(adView);
		xList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(), ArticleDetailActivity.class);
				intent.putExtra("url", alist.get(position-1).getLink());
				startActivity(intent);
			}
		});
		sImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				key = mEdit.getText().toString().trim();
				if (!TextUtils.isEmpty(key)) {
					pBar.setVisibility(View.VISIBLE);
					
					if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
						new AsyGetBlogList().execute(blogurl+"/?keyword="+key+"&&page="+pager,FLAG_ARTICLE_LOAD);
					}else {
						Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
					}
					
				}
			}
		});
	}
	
	private void initView(){
		mEdit = (EditText) findViewById(R.id.search_edit);
		sImage = (ImageView) findViewById(R.id.search_button);
		xList = (XListView) findViewById(R.id.search_result_list);
		pBar = (ProgressBar) findViewById(R.id.search_progress);
		adlayout = (LinearLayout) findViewById(R.id.adLayout);
	}
	
	
	/**
	 * ArticleList异步请求
	 * @author kutear
	 *
	 */
	class AsyGetBlogList extends AsyncTask<String, String, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			if (result!=null) {
				ArrayList<ArticleDetail> addlist = JsoupUtils.GetBlogList(result);
				if (addlist.size()>0) {
					//刷新
					if (params[1].equals(FLAG_ARTICLE_REFUSH)) { //判断是通过刷新还是加载得到的数据
						boolean flag = false;   //判断是否加载新数据的标志
						for (int i = addlist.size()-1; i>=0;i--) {
							//判断是否已经存在
							if (!Contains(addlist.get(i))) {
								alist.add(0,addlist.get(i));
								flag = true;
							}
						}
						if (!flag) {  //加载到的数据都是重复的
							publishProgress(FLAG_ARTICLE_NODATA);
						}
						//加载	
					}else {
						boolean flag = false;   //判断是否加载新数据的标志
						for (int i = addlist.size()-1; i>=0;i--) {
							if (!Contains(addlist.get(i))) {
								alist.add(addlist.get(i));
								flag = true;
							}
						}
						if (!flag) {
							publishProgress(FLAG_ARTICLE_NODATA);
						}
					}
				}else {
					publishProgress(FLAG_ARTICLE_NODATA);
				}

				for (ArticleDetail d:alist) {
					System.out.println("articletitle"+d.getTitle());
				}
				publishProgress("");
			}
			return null;
		}

		//判断listarray中是否包含某个对象
		public boolean Contains(ArticleDetail a){
			for (int i = 0; i < alist.size(); i++) {
				if (alist.get(i).getId()==a.getId()) {
					return true;
				}
			}
			return false;
		}


		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			Log.v(">>>>>>>", "onprogressUpdate");
			if (values[0].equals(FLAG_ARTICLE_NODATA)) {
				Toast.makeText(getApplicationContext(), "no more data", 0).show();
				return ;
			}
			adapter.notifyDataSetChanged();
			xList.setPullLoadEnable(true);
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//停止刷新...setting time
			xList.stopLoadMore();
			xList.stopRefresh();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			xList.setRefreshTime(time);
			adapter.notifyDataSetChanged();
			pBar.setVisibility(View.GONE);
		}
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (mEdit.getText().toString().equals("")) {
			xList.stopLoadMore();
			Toast.makeText(getApplicationContext(), "你还没有输入关键字呢,亲", 0).show();
			return ;
		}
		pager++;
		new AsyGetBlogList().execute(blogurl+"/?keyword="+key+"&page="+pager,FLAG_ARTICLE_LOAD);
	}
}
